<?php
namespace Kcdns\Service\User;

class Mcard extends \Think\Model
{

    static $instace;

    protected $name = 'user_card';

    const STATUS_ENABLE=1;

    const STATUS_DISABLE=2;

    protected $status_label=array(
        self::STATUS_ENABLE=>'已激活',
        self::STATUS_DISABLE=>'已禁用'
    );

    public static function getInstance ()
    {
        return self::$instace ?  : (self::$instace = new self());
    }

    public function add_ ($suid, $cardInfo)
    {
        $suid = OE('util')->validate($suid, 'required;int');
        $cardInfo = OE('util')->validate($cardInfo, array(
                'title' => 'required',
                'cover' => 'required',
                'building_id' => '',
                'description' => ''
        ));

        //打算店铺会员卡或者普通店铺会员卡
        $cardInfo['suid'] = $suid;
        $cardInfo['status'] = 1;
        $cardInfo['create_time'] = date('Y-m-d H:i:s');

        if(!is_numeric($cardInfo['cover'])){
            $cardInfo['cover'] = mediaToLocal($cardInfo['cover']);
        }
        return $this->data($cardInfo)->add();
    }

    public function edit ($suid, $cardInfo)
    {
        $suid = OE('util')->validate($suid, 'required;int');
        $cardInfo = OE('util')->validate($cardInfo, [
                'id' => 'required;int',
                'title' => 'required;',
                'cover' => 'required',
                'building_id' => '',
                'description' => '',
                'status' => 'enum=1,2'
        ]);
        
        $cardInfo['suid'] = $suid;

        if(!is_numeric($cardInfo['cover'])){
            $cardInfo['cover'] = mediaToLocal($cardInfo['cover']);
        }

        return $this->data($cardInfo)->where(['id' => $cardInfo['id']])->save() !== false;
    }

    public function remove ($suid, $cardId)
    {
        $suid = OE('util')->validate($suid, 'required;int');
        // $cardId = OE('util')->validate($cardId, '');
        $arr = [];
        foreach ($cardId as $k => $v) {
            $arr[$v] = OE('util')->validate($v, 'required;int');
        }
        $cardId = $arr;

        if (empty($cardId)) {
            throw new \Exception("参数错误");
        }
        // 会员卡持有数量
        $cardUse = M('user_account')->where(array(
                'card_id' => ['in', $cardId]
        ))->count();

        if ($cardUse)
        {
            throw new \Exception("会员卡正在使用中, 不能删除");
        }

        return $this->where(array(
                'id' => ['in', $cardId],
                'suid'=> $suid
        ))->delete() !== false;
    }

    public function list_ ($suid, $type = 2, $building = 0)
    {
        $suid = OE('util')->validate($suid, 'required;int');
        
        $where = array(
            'suid' => $suid
        );
        $type == 3 and $where['building_id'] = ['gt', 0];
        $building and $where['building_id'] = $building;

        $count = $this->where($where)->count();
        $data = $this->where($where)->limit(0, 99)->select() ?: [];
        foreach($data as &$item){
           $item=$this->_format($item);
        }
        return compact('count', 'data');
    }

    public function get ($cardId)
    {
        OE('util')->validate($cardId, 'required;int');
        $card= $this->where(array(
                'id' => $cardId,
        ))->find();

        return $this->_format($card);
    }


    public function listu ($userId, $type = 2)
    {
        $userId = OE('util')->validate($userId, 'required;int');
    
        $join = "a LEFT JOIN __USER_CARD__ b ON a.card_id=b.id";
        $where = array(
                'uid' => $userId,
                'type' => $type
        );
    
        //$count = M('user_account')->join($join)->where($where)->count();
        $data = M('user_account')->field('a.*,title,cover')->join($join)->where($where)->order('a.create_time DESC')->select() ?: [];

        $key = $type == 2 ? 'suid' : 'building_id';
        $sid = $type == 2 ? 'suid' : 'building_id';
        $cardId = $type == 2 ? 'suid' : 'building_id';
        $card_id_array = [2];

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $data[$k]['status_label'] = $v['status'] ? '已激活' : '已冻结';
                $card_id_array[$v[$key]] = $v[$key];
            }
        }

        if ($type == 2) {
            // 获得未申请的
            $card = M('UserCard')->where(['suid' => ['not in', $card_id_array]])->select() ?: [];
            $card_array = [];
            if (!empty($card)) {
                foreach ($card as $k => $v) {
                    $c = O('goods')->getList(2, array('uid' => $v['suid'], 'card_id' => $v['id'], 'account_type' => 2));
                    if (0 == count($c)) {
                        unset($card[$k]);
                        continue;
                    }

                    $c = arraySort($c, 'price', 'asc');
                    if (!isset($card_array[$v['suid']]) or (isset($card_array[$v['suid']]) && $card_array[$v['suid']]['price'] > $c[0]['price'])) {
                        $card_array[$v['suid']] = $v;
                    } else {
                        unset($card[$k]);
                    }
                }
            }
        } else {
            // 获得未申请的
            $field = 'id,building_id,title,cover';
            $card = M('UserCard')->where([$sid => ['not in', $card_id_array]])->getField($field) ?: [];
            $card_array = [];
            if (!empty($card)) {
                $card_id = [];
                foreach ($card as $k => $v) {
                    $card_id[$v[$sid]] = $v[$sid];
                }
                $goods = O('goods')->getList(2, array($cardId => ['in', $card_id], 'account_type' => $type)) ?: [];

                foreach ($goods as $k => $v) {
                    if (!isset($card_array[$v[$key]]) or (isset($card_array[$v[$key]]) && $card_array[$v[$key]]['price'] > $v['price'])) {
                        $card_array[$v[$key]] = $v;
                        $card_array[$v[$key]]['title'] = $card[$v['card_id']]['title'];
                        $card_array[$v[$key]]['cover'] = $card[$v['card_id']]['cover'];
                        $card_array[$v[$key]][$cardId] = $card[$v['card_id']][$key];
                        $card_array[$v[$key]]['id']    = $card[$v['card_id']]['id'];
                        ($card_array[$v[$key]]['title'] and $v['card_title']) or $card_array[$v[$key]]['title'] = $v['card_title'];
                    } else {
                        unset($goods[$k]);
                    }
                }
            }
        }
        $data  = array_merge($data, $card_array);
        $count = count($data);
        return compact('count', 'data');
    }
    
    public function listur ($userId)
    {
        $userId = OE('util')->validate($userId, 'required;int');
    
        $join = "a LEFT JOIN __USER_ACCOUNT__ b ON b.card_id=a.id AND b.uid='{$userId}'";
        $where = array(
                'a.activation_status'=>1,
                'a.suid'=>[
                        'neq',
                        PLATFORM_USER_ID
                ],
                'b.id'=>[
                        'exp',
                        'is null'
                ]
        );
        
    
        $count = M('user_card')->join($join)->where($where)->count();
        $data = M('user_card')->field('a.*')->join($join)->where($where)->order('a.create_time DESC')->select();
    
        foreach ($data as $k => $v)
        {
            //$data[$k]['status_label'] = $v['status'] ? '已激活' : '已冻结';
        }
    
        return compact('count', 'data');
    }

    public function infou($userId, $accountId, $suid = 0)
    {

        
            $join = "a LEFT JOIN __USER_CARD__ b ON a.card_id=b.id";
            $where = array(
                'a.uid' => $userId,
                'a.id' => $accountId
            );
            $data = M('user_account')->field('a.*,title,cover')->join($join)->where($where)->find();
            if (!$data) {
                $data = M('user_card')->field('*')->where(['id' => $accountId])->find();
                if (!$data) {
                    throw new \Exception('会员卡无效');
                }
            }

            $shop = M('shop')->where(array(
                'status' => 1,
                'uid' => $data['suid'],
                'activation_status' => 1,
            ))->order('')->select();
            foreach ($shop as $k => $v) {
                $data['shop'][$v['id']] = $v['title'];
            }

            if ($data['building_id']) {
                $data['building'] = O('shop')->getBuilding($data['building_id']);
            }

            $data['status_label'] = $data['status'] ? '已激活' : '已冻结';
        
        return $data;
    }
    
    protected function _format($cardInfo=array()){
        $cardInfo['status_label'] = $this->status_label[$cardInfo['status']];
        $cardInfo['handle_label'] = $cardInfo['status'] == self::STATUS_DISABLE ? '启用' : '停用';
        return $cardInfo;
    }
}